import axios from 'axios';
import { Message } from 'element-ui';
import router from '@/router/index.js';

const service = axios.create({
    timeout:50000,
    headers:{
        'X-Requested-With': 'XMLHttpRequest'
    }
})
/*
 *增加请求拦截器
*/
service.interceptors.request.use((config) => {
    //预处理请求的信息
    if(config.method==='post'){
        config.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
    }
    if (process.env.NODE_ENV === 'development') {
        config.url = '/api' + config.url;
    }
    if (sessionStorage.getItem("tokenId")){
        config.url = config.url + `?tokenId=${sessionStorage.getItem("tokenId")}`
    }
    return config
},(error) =>{
    //预处理请求有异常error时抛出错误
    return Promise.reject(error)
});
/*
*增加响应拦截器
*/
service.interceptors.response.use((response) => {
    if (response.status===200) {
        if (response.data.statusCode=== "200") {
             return response.data
        }else{
            Message.error(response.data.desc);
            return Promise.reject(response.data);
        }
    }else{
        return Promise.reject(response.status)
    }
},error =>{
    if (error.response) {
        switch (error.response.status) {
            case 401:
                router.replace({
                    path: '/login',
                    query: {
                        redirect: router.history.current.fullPath
                    }
                })
            break;
            case 504:
            case 404:
                Message.error('接口出错');
            break;
            default:
            Message.error('加载失败！ 请重新加载...');
            break;
        }
    }
    if (error == "Error: timeout of 5000ms exceeded") {
         Message.error('接口请求超时');
    }
    return Promise.reject(error)
})
export default service;
